import os
import requests
from datetime import datetime

from flask import current_app
from werkzeug.utils import secure_filename

from extensions import db
from models import Image


def download_image(image_url, ip=None):
    try:
        response = requests.get(image_url, timeout=5)
        if response.status_code == 200 and 'image' in response.headers['Content-Type']:
            ext = image_url.split('.')[-1].split('?')[0]
            timestamp = datetime.now().strftime('%Y%m%d%H%M%S%f')
            filename = secure_filename(f"img_{timestamp}.{ext}")
            folder = os.path.join(current_app.root_path, 'static', 'upload')
            os.makedirs(folder, exist_ok=True)
            filepath = os.path.join(folder, filename)
            with open(filepath, 'wb') as f:
                f.write(response.content)

            img = Image(filename=filename,
                        filepath=f'/static/upload/{filename}',
                        source_url=image_url,
                        upload_ip=ip)
            db.session.add(img)
            db.session.commit()

            return f'/static/upload/{filename}'
    except Exception as e:
        print(f"图片下载失败: {e}")
    return None
